package cn.monkey.io.transport.mq.codec;

import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class JsonObjectCodec implements Codec {
    private final Class<?> type;

    private final Gson gson;

    public JsonObjectCodec(Class<?> type, Gson gson) {
        this.type = type;
        this.gson = gson;
    }

    @Override
    public Object decode(byte[] bytes) {
        try (InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(bytes))) {
            return this.gson.fromJson(reader, this.type);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] encode(Object o) {
        return this.gson.toJson(o).getBytes();
    }
}
